import React, { Component, Fragment } from 'react'
import { connect } from 'react-redux'
import { Link } from 'react-router-dom'
// import { toJS } from 'immutable'
import { throttle } from '../../utils/throttle'
import { actionCreators } from './store'
import { BackgroundImg } from './background'
import {
  HeaderWrapper,
  HeaderLogo,
  HeaderNavWrapper,
  HeaderNavItem,
  NavItemTabWrapper,
  NavItemTabItem,
  NavBtn,
  BackgroundWrapper,
  SmallImg,
} from './style'

let timer = null
class Header extends Component {
  constructor(props) {
    super(props)
    this.state = {
      navTf: '',
      smallNavStyle: '',
      themeValue: parseInt(window.localStorage.getItem('themeValue') || 150601),
      themeTf: false,
    }
  }
  render() {
    const { headerNavList } = this.props
    return (
      <Fragment>
        <SmallImg className="small-img"></SmallImg>
        {
          this.state.themeValue === 150601 ?
            <BackgroundWrapper>
              <BackgroundImg backList={this.props.backList}></BackgroundImg>
            </BackgroundWrapper> : ''
        }
        <header>
          <HeaderWrapper>
            <HeaderLogo />
            {
              this.state.navTf === '2' || this.state.navTf === '3' ?
                this.headerNavList(headerNavList, '2') : ''
            }
            <NavBtn tf={this.state.smallNavStyle === 'header-navbar' ? 'click' : ''} onClick={this.navBtnClick.bind(this)}>
              <span className="iconfont">&#xe62a;</span>
            </NavBtn>
          </HeaderWrapper>
          {
            this.state.navTf === '1' || this.state.navTf === '3' ?
              this.headerNavList(headerNavList, '1') : ''
          }
        </header>
      </Fragment>
    )
  }
  headerNavList(data, tf = '1') { // 导航栏列表
    const datas = data.toJS()
    const navItem = datas.map(item => {
      return (
        <HeaderNavItem
          key={item.id}
          className={tf === '1' ? 'child_item' : ''}
        >
          <Link to="/">
            <i
              dangerouslySetInnerHTML={{ __html: item.icon }}
              className={item.value === 1506 ? 'iconfont icon-run' : 'iconfont'}
            />
            {item.name}
          </Link>
          {
            item.child_tab.length ?
              <NavItemTabWrapper onClick={this.navItemTabClickHandle.bind(this)} className={tf === '1' ? "child_tab" : 'child_tabb'}>
                {
                  item.child_tab.map(citem => {
                    return (
                      <NavItemTabItem data-cvalue={item.value} data-value={citem.value} key={citem.id}>
                        {citem.name}
                      </NavItemTabItem>
                    )
                  })
                }
              </NavItemTabWrapper> : ''
          }
        </HeaderNavItem >
      )
    })
    return (
      <HeaderNavWrapper className={tf === '1' ? this.state.smallNavStyle : ''} size={tf === '2' ? 'big' : 'small'}>
        {navItem}
      </HeaderNavWrapper >
    )
  }
  componentDidMount() { //组件创建
    this.createHeaderNav(true)
    this.props.getBackgroundList.call(this)
    window.addEventListener('resize', throttle(this.createHeaderNav.bind(this, false), 1000)) // 监听窗口宽度变化
    window.addEventListener('resize', throttle(this.backgroundImgAnimate.bind(this, false), 1000))
  }
  componentWillUnmount() { // 组件销毁时移除事件
    window.removeEventListener('resize', throttle(this.createHeaderNav.bind(this, false), 1000))
    window.removeEventListener('resize', throttle(this.backgroundImgAnimate.bind(this, false), 1000))
  }
  navItemTabClickHandle(e) { //导航栏点击
    const cValue = parseInt(e.target.getAttribute('data-cvalue')) || ''
    const value = parseInt(e.target.getAttribute('data-value')) || ''
    if (cValue) {
      const data = this.props.headerNavList.toJS()
      const item = data.filter(item => item.value === cValue)[0]
      if (item.name === '主题切换') {
        const themeValue = value
        window.localStorage.setItem('themeValue', themeValue)
        this.setState(({
          themeValue: themeValue,
        }), () => {
          this.backgroundImgAnimate()
        })
      }
    }
  }
  backgroundImgAnimate(tf=true) { //背景图切换
    let data = this.props.backList.toJS()
    if (window.innerWidth > 878) {
      if (this.state.themeValue === 150601 && !this.state.themeTf) {
        if (tf || timer === null) {
          this.bigShow(data)
        }
      } else if (this.state.themeValue === 150602) {
        this.smallShow(data)
      }
    } else {
      this.smallShow(data)
    }
  }
  bigShow(data) { //特效背景图展示
    this.setState({
      themeTf: true
    })
    let len = data.length - 1
    this.backgroundHandle(data, len, data.length - 1)
    timer = setInterval(() => {
      if (len <= 0) {
        len = data.length - 1
      } else {
        len--
      }
      this.backgroundHandle(data, len, data.length - 1)
    }, 10960)
  }
  smallShow(data) { //无特效背景图展示
    clearInterval(timer)
    timer = null
    this.setState({
      themeTf: false
    })
    data.forEach(item => {
      item.active = ''
    })
    this.props.changeBackground(data)
  }
  backgroundHandle(data, len, max_len) { //背景图切换处理
    if (data.length) {
      data[len].active = 'back-img-run'
      if (len === max_len) {
        data[0].active = ''
      } else {
        data[len + 1].active = ''
      }
      if (len === 0) {
        data[max_len].active = 'back-img-next-run'
      } else {
        data[len - 1].active = 'back-img-next-run'
      }
      this.props.changeBackground(data)
    }
  }
  createHeaderNav(tf = false) { // 判断宽度建立导航栏
    const { navTf } = this.state
    if (tf) {
      if (window.innerWidth < 878) {
        if (navTf === '') {
          this.setState({
            navTf: '1'
          })
        }
      } else {
        this.setState({
          navTf: '2'
        })
      }
    } else {
      if (navTf !== '3') {
        this.setState({
          navTf: '3'
        })
      }
    }
  }
  navBtnClick() { // 小导航栏按钮点击
    this.setState({
      smallNavStyle: this.state.smallNavStyle === 'header-navbar' ? '' : 'header-navbar'
    })
  }
}

const headerState = (state) => {
  return {
    headerNavList: state.getIn(['header', 'headerNavList']), //导航栏列表数据
    backList: state.getIn(['header', 'backList']),// 背景图列表数据
  }
}

const headerDispatch = (dispatch) => {
  return {
    async getBackgroundList() {
      const action = actionCreators.getBackList()
      await dispatch(action)
      this.backgroundImgAnimate(true)
    },
    changeBackground(data) {
      const action = actionCreators.changeBackground(data)
      dispatch(action)
    }
  }
}

export default connect(headerState, headerDispatch)(Header)